using UnityEngine;
using AI.Graph;

[CreateNodeMenu ("States/Patrol")]
public class PatrolState : State {

    [ParameterType (typeof (AIPath))]
    public ExposedParameter aiPathParameter;

    [ParameterType (typeof (NavMeshMovement))]
    public ExposedParameter navMeshMovementParameter;

    public float speed = 1;
    public float changePointThreshold = 0.2F;

    private AIPath aiPath;
    private NavMeshMovement navMeshMovement;
    private int currentPathIndex;
    private float lastSpeed;

    private bool pathPendingDown;


    protected override void OnStateEnter (AIBehaviour aiBehaviour) {
        aiBehaviour.TryGetExposedObject (aiPathParameter, out aiPath);
        aiBehaviour.TryGetExposedObject (navMeshMovementParameter, out navMeshMovement);

        if (aiBehaviour.TryGetExposedObject (navMeshMovementParameter, out navMeshMovement)) {
            lastSpeed = navMeshMovement.speed;
        }
        else {
            Debug.Log ("No NavMeshMovement found on Patrol State");
        }

        if (!aiBehaviour.TryGetExposedObject (aiPathParameter, out aiPath)) {
            Debug.Log ("No AIPath found on Patrol State");
        }

        if (navMeshMovement != null && aiPath != null) {
            navMeshMovement.NearestDestination (aiPath.points, out currentPathIndex);
        }
    }


    protected override void OnStateUpdate (AIBehaviour aiBehaviour) {
        if (navMeshMovement != null && aiPath != null) {
            navMeshMovement.speed = speed;

            if (navMeshMovement.remainingDistance <= changePointThreshold) {
                if (aiPath.isPathClosed) {
                    currentPathIndex++;
                    if (currentPathIndex >= aiPath.numPoints) {
                        currentPathIndex = 0;
                    }
                }
                else {
                    if (pathPendingDown) {
                        currentPathIndex--;
                        if (currentPathIndex < 0) {
                            currentPathIndex = 0;
                            pathPendingDown = false;
                        }
                    }
                    else {
                        currentPathIndex++;
                        if (currentPathIndex >= aiPath.numPoints) {
                            currentPathIndex = aiPath.numPoints - 1;
                            pathPendingDown = true;
                        }
                    }
                }
            }

            navMeshMovement.MoveToDestination (aiPath[currentPathIndex]);
        }
    }


    protected override void OnStateExit (AIBehaviour aiBehaviour) {
        if (navMeshMovement != null) {
            navMeshMovement.speed = lastSpeed;
        }
    }

}